<template>
  <Drawer
    v-model="show"
    :title="title"
    :size="500"
    @close="show = false"
  >
    <template #content>
      <el-form
        label-width="150px"
        :model="form"
        :rules="rules"
        ref="formRef"
        v-loading="formLoading"
      >
        <el-form-item label="所属企业" prop="enterId">
          <el-select
            filterable
            v-model="form.enterId"
            placeholder="请选择所属企业"
            @change="tenantChange"
            class="!w-250px"
          >
            <el-option
              v-for="item in tenantList"
              :key="item.id"
              :label="item.enterName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户企业" prop="cusId">
          <el-select
            filterable
            v-model="form.cusId"
            placeholder="请选择客户企业"
            class="!w-250px"
          >
            <el-option
              v-for="item in customerList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="startTime">
          <el-date-picker
            type="datetime"
            v-model="form.startTime"
            placeholder="请选择生效时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="失效时间" prop="endTime">
          <el-date-picker
            type="datetime"
            v-model="form.endTime"
            placeholder="请选择失效时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="common" @click="closeDrawer">
        取消
      </el-button>
      <el-button
        type="primary"
        :disabled="formLoading"
        @click="submitPlan"
      >
        确认
      </el-button>
    </template>
  </Drawer>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash'
import { formatDate } from '@/utils/formatTime'
import * as salesPlanApi from '@/api/salesPlan'
import * as authorizationManageApi from '@/api/authorizationManage'

const title = ref('新增')
const formRef = ref()
const show = ref(false)
const message = useMessage()
const formLoading = ref(false)
const emit = defineEmits(['success'])
const form: Record<string, any> = ref({
  enterId: undefined,
  cusId: undefined,
  startTime: undefined,
  endTime: undefined
})

const validStartTime = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请选择生效时间'))
  }
  if (!form.value.endTime) {
    return callback()
  }
  const startTimeStmp = new Date(value).getTime()
  const endTimeStmp = new Date(form.value.endTime).getTime()
  if (startTimeStmp > endTimeStmp) {
    return callback(new Error('生效时间不能晚于失效时间'))
  }
  return callback()
}
const validEndTime = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请选择失效时间'))
  }
  if (!form.value.startTime) {
    return callback()
  }
  const startTimeStmp = new Date(
    form.value.startTime
  ).getTime()
  const endTimeStmp = new Date(value).getTime()
  if (startTimeStmp > endTimeStmp) {
    return callback(new Error('失效时间不能早于生效时间'))
  }
  return callback()
}
const rules = reactive({
  enterId: [
    {
      required: true,
      message: '请选择所属企业',
      trigger: 'change'
    }
  ],
  cusId: [
    {
      required: true,
      message: '请选择客户企业',
      trigger: 'change'
    }
  ],
  startTime: [
    {
      required: true,
      message: '请选择生效时间',
      trigger: 'change'
    },
    { validator: validStartTime, trigger: 'change' }
  ],
  endTime: [
    {
      required: true,
      message: '请选择失效时间',
      trigger: 'change'
    },
    { validator: validEndTime, trigger: 'change' }
  ]
})
const tenantList: Record<string, any> = ref([])
const customerList: Record<string, any> = ref([])

const open = async () => {
  resetForm()
  form.value.startTime = formatDate(new Date())
  form.value.endTime = '2099-01-01 00:00:00'
  getTenantList()
  show.value = true
}

const getTenantList = async () => {
  try {
    formLoading.value = true
    const res =
      await authorizationManageApi.getOutTenantListByIdentity(
        { identity: 1 }
      )
    tenantList.value = res || []
  } finally {
    formLoading.value = false
  }
}

const tenantChange = () => {
  customerList.value = []
  form.value.cusId = undefined
  if (form.value.enterId) {
    getCustomerList()
  }
}

const getCustomerList = async () => {
  const res =
    await authorizationManageApi.getCustomerListByIdentity({
      outTenantId: form.value.enterId,
      identity: 1
    })
  customerList.value = res || []
}

const router = useRouter()
const submitPlan = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true
    const data = cloneDeep(form.value)
    data.startTime = formatDate(data.startTime)
    data.endTime = formatDate(data.endTime)
    const res = await salesPlanApi.addsaleplan(data)
    if (res.code === 0) {
      message.success('新增成功')
      emit('success')
    } else if (res.code === 100910003) {
      await message.confirm(res.msg)
      refreshAuthorize()
    } else if (res.code === 100910004) {
      await message.confirm(res.msg)
      router.push({path: '/authManageCatalog/authorizationManage'})
    } else {
      message.error(res.msg)
    }
    closeDrawer()
  }finally {
    formLoading.value = false
  }
}
const refreshAuthorize = async () => {
  await salesPlanApi.refreshAuthorize()
}
const closeDrawer = () => {
  show.value = false
}

const resetForm = () => {
  tenantList.value = []
  customerList.value = []
  form.value = {
    enterId: undefined,
    cusId: undefined,
    startTime: undefined,
    endTime: undefined
  }
  formRef.value?.resetFields()
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
:deep(.el-date-editor--datetime .el-input__wrapper) {
  width: 250px;
}
</style>
